package com.liuzh.websocket.dao;

import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.google.gson.Gson;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * Created by liuzh on 2017/10/12.
 */
@Repository
public class DaoImpl<T> implements Dao<T>{

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public T save(T o) throws Exception {
        entityManager.persist(o);
        return o;
    }

    @Override
    public T update(T o) throws Exception {
        T merged = entityManager.merge(o);
        return merged;
    }

    @Override
    public T delete(T o) throws Exception {
        entityManager.remove(o);
        return o;
    }

    @Override
    public T query(Class<T> clazz, int primaryKey) throws Exception {
        return entityManager.find(clazz, primaryKey);
    }
    
    @Override
    public T query(Class<T> clazz, Long primaryKey) throws Exception {
    	return entityManager.find(clazz, primaryKey);
    }

	@Override
    public List<Map<String, Object>> querySql(String sql) throws Exception {
        Query query = this.entityManager.createNativeQuery(sql);
        /**
         * 设置返回值为map类型
         */
        query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        List<Map<String, Object>> list = query.getResultList();
        return list;
    }
	
	@Override
	public Map<String, Object> querySqlOne(String sql) throws Exception {
		Query query = this.entityManager.createNativeQuery(sql);
		/**
		 * 设置返回值为map类型
		 */
		query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		
		Map<String, Object> map = (Map<String, Object>) query.getSingleResult();
		return map;
	}

    @Override
	public T querySqlOne(Class<T> clazz, String sql) throws Exception {
    	 Map<String, Object> map = querySqlOne(sql);
		return new Gson().fromJson(new Gson().toJson(map), clazz);
	}

	@Override
    public List<Map<String, Object>> querySql(String sql, int page, int rows) throws Exception {
        Query query = entityManager.createNativeQuery(sql);
        query.setFirstResult(( (page>1?page:1) -1)*rows).setMaxResults(rows);
        /**
         * 设置返回值为map类型
         */
        query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

	@Override
	public int querySqlCount(String sql, int rows) throws Exception {
		Query query = entityManager.createNativeQuery(sql);
		return (int) Math.ceil((double)query.getResultList().size()/rows);
	}

	@Override
	public void updateSql(String sql) throws Exception {
		entityManager.createNativeQuery(sql).executeUpdate();
	}
	
	
}
